const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const OAuthTokenSchema = new Schema({
  'name': {
    type: String,
    required: true,
    trim: true
  },
  'access_token': {
    type: String,
    required: true,
    trim: true
  },
  'refresh_token': {
    type: String,
    required: true,
    trim: true
  },
  'openid': {
    type: String,
    required: true,
    trim: true
  },
  'scope': {
    type: String,
    required: true,
    trim: true
  },
  'expires_in': {
    type: Number,
    required: true
  },
  meta: {
    createdAt: {
      type: Number,
      default: new Date().valueOf()
    },
    updatedAt: {
      type: Number,
      default: new Date().valueOf()
    }
  }
});
OAuthTokenSchema.statics = {
  async getOAthToken(name) {
    const oauth = await this.findOne({
      name
    })
    if (oauth && oauth.access_token) {
      oauth.access_token = oauth.access_token;
      oauth.openid = oauth.openid;
      oauth.name = oauth.name;
    }
    return oauth;
  },
  async saveOAthToken(data) {
    let oauth = await this.findOne({
      name: data.name
    })
    if (!oauth) {
      oauth = new OAuth({
        'name': data.name,
        'access_token': data['access_token'],
        'refresh_token': data['refresh_token'],
        'openid': data['openid'],
        'scope': data['scope'],
        'expires_in': data['expires_in'],
        meta: {
          createdAt: new Date().valueOf(),
          updatedAt: new Date().valueOf()
        }
      })
    } else {
      oauth['expires_in'] = data['expires_in'];
      oauth['access_token'] = data['access_token'];
      oauth['refresh_token'] = data['refresh_token'];
      oauth['meta']['updatedAt'] = new Date().valueOf();
    }
    await oauth.save()
    return data;
  }
}
const OAuth = mongoose.model('OAuth', OAuthTokenSchema, 'OAuth');
